package service

import (
	"errors"
	"gin-demo/global"
	"gin-demo/model"
	"gorm.io/gorm"
	"strconv"
	"time"
)

// 拉黑jwt
func JsonInBlacklist(jwtList model.JwtBlacklist) (err error) {
	err = global.GN_DB.Create(&jwtList).Error
	return
}

// 判断JWT是否在黑名单内部
func IsBlacklist(jwt string) bool {
	isNotFound := errors.Is(global.GN_DB.Where("jwt = ?", jwt).First(&model.JwtBlacklist{}).Error, gorm.ErrRecordNotFound)
	return !isNotFound
}

// 从redis取jwt
func GetRedisJWT(userId uint64) (err error, redisJWT string) {
	key := global.GN_REDIS_KEY.Jwt.JwtKey + strconv.FormatUint(userId,20)
	redisJWT, err = global.GN_REDIS.Get(key).Result()
	return err, redisJWT
}

// jwt存入redis并设置过期时间
func SetRedisJWT(jwt string, userId uint64) (err error) {
	key := global.GN_REDIS_KEY.Jwt.JwtKey + strconv.FormatUint(userId,20)
	// 此处过期时间等于jwt过期时间
	timer := time.Duration(global.GN_CONFIG.JWT.ExpiresTime) * time.Second
	err = global.GN_REDIS.Set(key, jwt, timer).Err()
	return err
}

// 删除redis存的jwt
func DelRedisJWT(userId uint64)  (err error) {
	key := global.GN_REDIS_KEY.Jwt.JwtKey + strconv.FormatUint(userId,20)
	err = global.GN_REDIS.Del(key).Err()
	return err
}